'use strict';
const fs = require('fs');
const path = require('path');
const mongoose = require('mongoose');

const configuration = require('../commons/factories/configuration');
const logFactory = require('../commons/factories/logFactory');

const appLog = logFactory.getLogger('app');
const serverCfg = configuration.get('server');

mongoose.connect(serverCfg.mongo.db, serverCfg.mongo.options);

const db = mongoose.connection;

// MongoDB连接成功后回调，这里仅输出一行日志
db.on('connected', function () {
    appLog.info('mongoose已连接', serverCfg.mongo.db);
});

// MongoDB连接出错后回调，这里仅输出一行日志
db.on('error',function (err) {
    appLog.error('mongoose连接异常', err);
});

// MongoDB连接断开后回调，这里仅输出一行日志
db.on('disconnected', function () {
    appLog.info('mongoose已断开连接');
});

// 当前进程退出之前关闭MongoDB连接
process.on('SIGINT', function() {
    db.close(function () {
        appLog.info('进程关闭之前，mongoose连接关闭');
        process.exit(0);
    });
});

const MAPPING_DIR = path.join(__dirname, './mapping');

fs.readdirSync(MAPPING_DIR).forEach(function (file) {
    require(path.join(MAPPING_DIR, file));
    let fileNameParser = path.parse(file);
    if (fileNameParser.ext === '.js') {
        let modelName = fileNameParser.name;
        exports[modelName] = db.model(modelName);
    }
});
